<template>
  <el-form
      :model="searchParams"
      size="small"
      :rules="rules"
      class="zulinFormClass"
      ref="zulinFormRef"
      label-width="190px"
  >
    <el-row>
      <el-col :span="12">
        <el-form-item label="不动产坐落地址（省/市）" prop="bdcdzss">
          <el-cascader
              style="width:200px;"
              v-model="searchParams.bdcdzss"
              :options="addressOptions"
              :props="{ expandTrigger: 'hover' }"
              @change="handleChange"></el-cascader>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="不动产坐落地址（详细地址）" prop="bdczldzXxdz">
          <el-input
              style="width:200px;"
              size="small"
              :maxlength="80"
              v-model="searchParams.bdczldzXxdz"
              placeholder="请输入"
          ></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label-width="0">
          <el-col :span="11">
            <el-select v-model="searchParams.bdcdwdmSelect" placeholder="请选择" clearable
                       @change="handBdcdwdmChange()">
              <el-option label="不动产单位代码" value="01"></el-option>
              <el-option label="网签合同备案编号" value="02"></el-option>
            </el-select>
          </el-col>
          <el-col :span="13">
            <el-form-item label-width="0" prop="bdcdwTemp">
              <el-input v-model="searchParams.bdcdwTemp" :maxlength="28"/>
            </el-form-item>
          </el-col>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="跨地（市）标志" prop="kdsbz">
          <el-select
              size="small"
              v-model="searchParams.kdsbz"
              placeholder="请选择"
              style="width:200px;"

          >
            <el-option label="是" value="Y"></el-option>
            <el-option label="否" value="N"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="产权证书/不动产权证号">
          <el-input
              size="small"
              maxlength="40"
              v-model="searchParams.cqzsbh"
              placeholder="请输入"
              style="width:200px;"

          ></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="面积单位" prop="mjdw">
          <el-select
              size="small"
              v-model="searchParams.mjdw"
              placeholder="请选择"
              style="width:200px;"

          >
            <el-option label="平方米" value="平方米"></el-option>
            <el-option label="平方千米" value="平方千米"></el-option>
            <el-option label="公顷" value="公顷"></el-option>
            <el-option label="亩" value="亩"></el-option>
            <el-option label="h㎡" value="h㎡"></el-option>
            <el-option label="k㎡" value="k㎡"></el-option>
            <el-option label="㎡" value="㎡"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="土地增值税项目编号">
          <el-input
              size="small"
              maxlength="16"
              v-model="searchParams.tdzzsxmbh"
              placeholder="请输入"
              style="width:200px;"

          ></el-input>
        </el-form-item>
      </el-col>
      <!-- 18.2 -->
      <el-col :span="12">
        <el-form-item label="核定计税价格">
          <el-input
              @input="valitedNumber('hdjsjg')"
              size="small"
              maxlength="40"
              v-model="searchParams.hdjsjg"
              placeholder="请输入"
              style="width:200px;"

          ></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <!-- 18.2 -->
        <el-form-item label="实际成交含税金额">
          <el-input
              @input="valitedNumber('sjcjhsje')"
              size="small"
              maxlength="40"
              v-model="searchParams.sjcjhsje"
              placeholder="请输入"
              style="width:200px;"

          ></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">

        <el-form-item label="共同购买方标识">
          <el-select
              size="small"
              v-model="searchParams.dfgtgmbz"
              placeholder="请选择"
              style="width:200px;"
          >
            <el-option label="多方共同购买" value="Y"></el-option>
            <el-option label="非多方共同购买" value="N"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>


    <el-row v-if="searchParams.dfgtgmbz == 'Y'">
      <el-col :span="24">
        <div @click="add" class="worldBlueBtn">新增</div>
        <div @click="del" class="worldBlueBtn">删除</div>
        <tableList
            border
            maxHeight="200"
            :keySet="keySet"
            :autoHeight="true"
            :tableData="searchParams.tdywItemList"
            :radioSelect="true"
            rowKey="id"
            class="formTableListClass"
            @radioHandleCurrentChange="radioHandleCurrentChange"
        >
          <template #gtgmf="{row,index}">
            <div>
              <el-input size="small" v-model="row.gtgmf" @input="validateInput(index)" :maxlength="100"></el-input>
            </div>
          </template>
          <template #zjlx="{row}">
            <div>
              <!-- <el-input v-model="row.zjlx"></el-input> -->
              <el-select
                  size="small"
                  v-model="row.zjlx"
                  placeholder="请选择"
                  style="width:100%;"

              >
                <el-option v-for="(val,key) in CARDTYPE" :label="val" :value="key" :key="key"></el-option>
              </el-select>
            </div>
          </template>
          <template #zjhm="{row}">
            <div>
              <el-input size="small" v-model="row.zjhm" :maxlength="20"></el-input>
            </div>
          </template>
        </tableList>
      </el-col>

    </el-row>
  </el-form>
</template>

<script>
import tableList from '@/components/tableList/index.vue'
import {CARDTYPE} from '@/components/common/constant.js'
import VXETable from 'vxe-table'
import {getAddressList} from "@/api/handInvoiceAdd";

export default ({
  props: ['vmsManualTdywDtoList'],
  data() {
    return {
      timer: null,
      CARDTYPE,
      selected: null,
      searchParams: { // 新建是默认值, 编辑的话,进来覆盖一下默认值
        bdcdzss: [],
        bdczldzS: '',
        bdczldzS1: '',
        bdczldzXxdz: '',
        bdcdwdm: '',
        kdsbz: '',
        cqzsbh: '',
        mjdw: '',
        tdzzsxmbh: '',
        hdjsjg: '',
        sjcjhsje: '',
        dfgtgmbz: '',
        bdcdwdmSelect: '01',
        bdcdwTemp: '',

        tdywItemList: [], // 这个值是对象里的结构

      },
      keySet: [

        {
          label: '共同购买方',
          englishName: 'gtgmf',
          isSlot: true,
          slotName: "gtgmf",
          showOverflowTooltip: false,
        },
        {
          label: '证件类型',
          englishName: 'zjlx',
          isSlot: true,
          slotName: "zjlx",
          showOverflowTooltip: false,

        },
        {
          label: '证件号码',
          englishName: 'zjhm',
          isSlot: true,
          slotName: "zjhm",
          showOverflowTooltip: false,

        },

      ],
      rules: {
        bdcdzss: [
          {required: true, message: '请选择', trigger: 'change'}
        ],
        bdczldzXxdz: [
          {required: true, message: '请输入', trigger: 'change'}
        ],
        kdsbz: [
          {required: true, message: '请选择', trigger: 'change'}
        ],
        mjdw: [
          {required: true, message: '请选择', trigger: 'change'}
        ]
      },
      addressOptions: [],
    }
  },
  methods: {
    isAddress() {
      let addres = [
        '街',
        '路',
        '村',
        '乡',
        '镇',
        '道',
        '号',
        '巷',
      ]
      return addres.some(item => this.searchParams.bdczldzXxdz.includes(item))

    },
    async submitValidate() {

      let res = await this.$refs['zulinFormRef'].validate().catch((err) => {
        console.log(err);
        return false
      })
      if (res) {
        if (!Array.isArray(this.searchParams.tdywItemList)) return res;
        for (let index = 0; index < this.searchParams.tdywItemList.length; index++) {
          const element = this.searchParams.tdywItemList[index];
          if (!element.gtgmf) {
            res = false;
            return VXETable.modal.message({
              content: '共同购买方列表的第' + (index + 1) + '行的共同购买方不能为空！',
              status: 'error',
            })
          } else if (!element.zjlx) {
            res = false;
            return VXETable.modal.message({
              content: '共同购买方列表的第' + (index + 1) + '行的证件类型不能为空！',
              status: 'error',
            })
          } else if (!element.zjhm) {
            res = false;
            return VXETable.modal.message({
              content: '共同购买方列表的第' + (index + 1) + '行的证件号码不能为空！',
              status: 'error',
            })
          }
        }
      }
      if (this.isAddress() != true) {
        return VXETable.modal.message({
          content: '详细地址必须包含街、路、村、乡、镇、道、巷、号等任意一个关键词！',
          status: 'error',
        })
      }
      return res;
    },
    getFormValue() {
      // 返回之前对不动产单位编码进行处理
      if (this.searchParams.bdcdwdmSelect === '01') {
        this.searchParams.bdcdwdm = this.searchParams.bdcdwTemp
        this.searchParams.wqhtbabh = ''
      } else {
        this.searchParams.wqhtbabh = this.searchParams.bdcdwTemp
        this.searchParams.bdcdwdm = ''
      }
      return [this.searchParams];
    },
    del() {
      // 删除
      if (this.selected) {
        this.$message.success('删除成功')
        let res = this.searchParams.tdywItemList.filter(item => {
          return item.id != this.selected.id
        })
        console.log(res);
        this.searchParams.tdywItemList = res
      }
    },
    validateInput(index) {
      this.searchParams.tdywItemList[index].gtgmf = this.searchParams.tdywItemList[index].gtgmf.replace(/[^A-Za-z\u4E00-\u9FA5]/g, '')
      // 限制输入框只能输入汉字或者英文大小写字符
    },
    valitedNumber(key) {
      // 清除非数字或小数点以外的其他字符
      let cleanedValue = this.searchParams[key].replace(/[^0-9.]/g, '');
      // 检查小数点
      const parts = cleanedValue.split('.');
      if (parts.length === 2) {
        // 转换小数部分确保不超过两位
        parts[1] = parts[1].slice(0, 2);
        // 将整数部分控制在18位以内
        parts[0] = parts[0].slice(0, 16);
        // 重新组合字符串
        cleanedValue = `${parts[0]}.${parts[1]}`
      } else if (parts.length > 2) {
        // 有多余的小数点，保留第一个小数点之前的部分
        cleanedValue = parts[0] + '.' + parts.slice(1, parts.length).join('');
      } else {
        // 只保留18位整数
        cleanedValue = cleanedValue.slice(0, 16);
      }
      // 更新输入框的值
      this.searchParams[key] = cleanedValue;
    },
    add() {
      this.searchParams.tdywItemList.push({
        id: new Date().getTime() + Math.floor(Math.random() * 10000000000),
        gtgmf: "",
        zjlx: "",
        zjhm: "",
      })
      // 增加当前行
      // 指定一个对象初始化结构, 新增的时候,就直接push到数组.
    },
    radioHandleCurrentChange(val) {
      console.log(val)
      this.selected = val;
      // 删除,当前list里删除
    },
    handleChange(val) {
      this.searchParams.bdczldzS = val[0] || '';
      this.searchParams.bdczldzS1 = val[1] || '';
    },
    async getAddressData() {
      const {code, msg, data} = await getAddressList();
      if (code == 200) {
        this.addressOptions = data;
      }
    },
    handBdcdwdmChange() {
      this.searchParams.bdcdwTemp = ''
    }
  },
  components: {
    tableList
  },
  created() {
    this.timer = setTimeout(() => {
      clearTimeout(this.timer);
      this.timer = null;
    }, 1000)
    if (this.vmsManualTdywDtoList[0]) {
      this.searchParams = {
        ...this.searchParams,
        ...this.vmsManualTdywDtoList[0],
        hdjsjg: this.vmsManualTdywDtoList[0].hdjsjg && this.vmsManualTdywDtoList[0].hdjsjg.toString() || '',
        bdcdzss: [this.vmsManualTdywDtoList[0].bdczldzS, this.vmsManualTdywDtoList[0].bdczldzS1]
      };
      try {
        if (!this.searchParams.tdywItemList || this.searchParams.tdywItemList.length == 0) {
          this.searchParams.tdywItemList = this.vmsManualTdywDtoList[0].tdywItemVoList || [];
        }
      } catch (error) {

      }
    }
    this.getAddressData()
  },
  watch: {
    'searchParams.mjdw'(newV) {
      console.log(newV, '169');
      if (newV) {
        if (this.timer) return;
        this.$emit('editMJAndCQZS', {
          dw: newV
        })
      }
    },
    'searchParams.cqzsbh'(newV) {
      if (newV) {
        if (this.timer) return;
        this.$emit('editMJAndCQZS', {
          ggxh: newV
        })
      }
    },
  },
})
</script>

<style lang="scss" scoped>
.zulinFormClass {
  border: 1px solid #bb8c91;
  padding: 22px 6px 0;
  white-space: normal;

  ::v-deep {
    width: 100%;
  }

  .formTableListClass {
    ::v-deep .el-form-item--small.el-form-item {
      margin-bottom: 2px;
    }
  }
}
</style>
